package com.cloudxingkong.dianyinke.Student.Utils;

import android.content.ContentValues;
import android.content.Context;
import android.util.Log;
import android.util.Xml;
import android.widget.Toast;

import com.cloudxingkong.dianyinke.NewTeacher.Utils.MD5Utils;
import com.cloudxingkong.dianyinke.NewTeacher.config.Constans;
import com.tencent.mm.sdk.constants.Build;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;

import org.xmlpull.v1.XmlPullParser;

import java.io.StringReader;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;


/**
 * 微信支付工具类
 * @author hfk
 * create at 2016/5/3 10:33
 */
public class WxUtil {
    /**
     * 获取随机字符串
     * @return
     */
    public static String genNonceStr() {
        Random random = new Random();

        return MD5Utils.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
    }

    /**
     * 时间戳
     * @return
     */
    public static long genTimeStamp() {
        return System.currentTimeMillis() / 1000;
    }

    /**
     * 转化为XML格式
     * @param params
     * @return
     */
    public static String toXml(List<ContentValues> params) {
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        for (int i = 0; i < params.size(); i++) {
            for (Map.Entry<String, Object> entry : params.get(i).valueSet()) {
                sb.append("<"+entry.getKey()+">");
                sb.append(entry.getValue());
                sb.append("</"+entry.getKey()+">");
            }

        }
        sb.append("</xml>");

        Log.e("", sb.toString());
        return sb.toString();
    }

    /**
     * 解析xml并转化为Map<String,String>值
     * @param content
     * @return
     */
    public static Map<String,String> decodeXml(String content) {

        try {
            Map<String, String> xml = new HashMap<String, String>();
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(new StringReader(content));
            int event = parser.getEventType();
            while (event != XmlPullParser.END_DOCUMENT) {

                String nodeName=parser.getName();
                switch (event) {
                    case XmlPullParser.START_DOCUMENT:

                        break;
                    case XmlPullParser.START_TAG:

                        if("xml".equals(nodeName)==false){
                            //实例化student对象
                            xml.put(nodeName,parser.nextText());
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        break;
                }
                event = parser.next();
            }
            return xml;
        } catch (Exception e) {
            Log.e("orion",e.toString());
        }
        return null;

    }

    /**
     * 预支付交易会话Id获取  prepay_id
     * @param describe
     * @param money 商品金额，以分为单位
     * @return
     */
    /*public static String genProductArgs(String describe,String money) {
        StringBuffer xml = new StringBuffer();

        try {
            String	nonceStr = genNonceStr();
            xml.append("</xml>");
            List<ContentValues> packageParams = new LinkedList<ContentValues>();
            ContentValues c = new ContentValues();
            c.put("addid", Constans.APP_ID);
            c.put("body", describe);
            c.put("mch_id", Constans.MCH_ID);
            c.put("nonce_str", nonceStr);
            c.put("notify_url",Constans.NOTIFY_URL);
            c.put("out_trade_no",genNonceStr());
            c.put("spbill_create_ip",Constans.SPBILL_CREATE_IP);
            c.put("total_fee", money);
            c.put("trade_type", "APP");
            String sign = genPackageSign(packageParams);
            c.put("sign", sign);
            packageParams.add(c);
            *//*packageParams.add(new ContentValues().put("addid", Constans.APP_ID));//开放平台appid
            packageParams.add(new BasicNameValuePair("body", describe));      //商品描述
            packageParams.add(new BasicNameValuePair("mch_id", Constans.MCH_ID));//商户号
            packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));//随机字符串
            packageParams.add(new BasicNameValuePair("notify_url",Constans.NOTIFY_URL));//支付结果异步通知
            packageParams.add(new BasicNameValuePair("out_trade_no",genNonceStr()));//商家订单号
            packageParams.add(new BasicNameValuePair("spbill_create_ip",Constans.SPBILL_CREATE_IP));//用户公网ip
            packageParams.add(new BasicNameValuePair("total_fee", money));//商品金额，以分为单位
            packageParams.add(new BasicNameValuePair("trade_type", "APP"));//交易类型
            String sign = genPackageSign(packageParams);
            packageParams.add(new BasicNameValuePair("sign", sign));*//*
            String xmlstring = WxUtil.toXml(packageParams);
            return xmlstring;
        } catch (Exception e) {
            Log.e("TestActivity", "genProductArgs fail, ex = " + e.getMessage());
            return null;
        }
    }*/

    /**
     * 二次签名
     * @param iwxapi
     * @param req
     * @param resultunifiedorder
     */
    public static void genPayReq(IWXAPI iwxapi,PayReq req,
            Map<String,String> resultunifiedorder) {
        req.appId = Constans.APP_ID;
        req.partnerId = Constans.MCH_ID;
        req.prepayId = resultunifiedorder.get("prepay_id");
        req.packageValue="Sign=WXPay";
        req.nonceStr = genNonceStr();
        req.timeStamp = String.valueOf(genTimeStamp());

        List<ContentValues> signParams = new LinkedList<ContentValues>();
        ContentValues contentValues = new ContentValues();
        contentValues.put("appid", req.appId);
        contentValues.put("noncestr", req.nonceStr);
        contentValues.put("package", req.packageValue);
        contentValues.put("partnerid", req.partnerId);
        contentValues.put("prepayid", req.prepayId);
        contentValues.put("timestamp", req.timeStamp);
        signParams.add(contentValues);

        req.sign = genAppSign(signParams);
        Log.e("orion3", signParams.toString());
        Log.e("orion3.1",req.sign.toString()+"");
        sendPayReq(iwxapi,req);
    }

    /**
     *  检测是否有微信与是否支持微信支付
     * @return
     */
    public static boolean check(Context context,IWXAPI api) {
        boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
        if(!api.isWXAppInstalled())
        {
            Toast.makeText(context,"没有安装微信",Toast.LENGTH_SHORT).show();
            return false;
        }
        if(!api.isWXAppSupportAPI())
        {
            Toast.makeText(context,"你使用的微信版本不支持微信支付！",Toast.LENGTH_SHORT).show();
            return false;
        }
        return isPaySupported;
    }

    /**
     * 生成签名
     * @param params 
     * @return
     */
    public static String genPackageSign(List<ContentValues> params) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < params.size(); i++) {
            for (Map.Entry<String, Object> entry : params.get(i).valueSet()) {
                sb.append(entry.getKey());
                sb.append('=');
                sb.append(entry.getValue());
                sb.append('&');
            }
        }
        sb.append("key=");
        sb.append(Constans.API_KEY);
        String packageSign = MD5Utils.getMessageDigest(sb.toString().getBytes()).toUpperCase();
        Log.e("orion4",packageSign);
        return packageSign;
    }

    /**
     *  得到app签名
     * @param params
     * @return
     */
    public static String genAppSign(List<ContentValues> params) {
        StringBuilder sb = new StringBuilder();
//        ,StringBuilder stringBuilder
        for (int i = 0; i < params.size(); i++) {
            for (Map.Entry<String, Object> entry : params.get(i).valueSet()) {
                sb.append(entry.getKey());
                sb.append('=');
                sb.append(entry.getValue());
                sb.append('&');
            }
        }
        sb.append("key=");
        sb.append(Constans.API_KEY);
//        stringBuilder.append("sign str\n"+sb.toString()+"\n\n");
        String appSign = MD5Utils.getMessageDigest(sb.toString().getBytes());
        Log.e("orion5",appSign);
        return appSign;
    }

    /**
     * 微信注册app
     * @param iwxapi
     * @param req
     */
    public static void sendPayReq(IWXAPI iwxapi,PayReq req) {
        if (iwxapi != null) {
            iwxapi.registerApp(Constans.APP_ID);
            iwxapi.sendReq(req);
        }
    }
}